﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Store;
using SIG.Model;
using SIG.Model.Enums;
using SIG.Model.Store;
using SIG.Resources;
using SIG.Resources.Admin;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Store;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class GoodsCategoryController : BaseController
    {
        // GET: Admin/GoodsCategory
        private readonly IGoodsCategoryService _goodsCategoryService;
        private readonly IPageMetaService _pageMetaService;
        private IMapper _mapper;
        public GoodsCategoryController(IGoodsCategoryService goodsCategoryService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _goodsCategoryService = goodsCategoryService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;


        }

        // GET: Admin/Pages
        public ActionResult Index(int? page, string keyword)
        {
            var categoryListVM = new GoodsCategoryListVM();

            categoryListVM.Keyword = keyword;
            categoryListVM.PageIndex = (page ?? 1) - 1;
            categoryListVM.PageSize = SettingsManager.Store.PageSize;
            int totalCount;
            var categorylist = _goodsCategoryService.GetPagedElements(categoryListVM.PageIndex, categoryListVM.PageSize, categoryListVM.Keyword, out totalCount);
            var categoryVMList = _mapper.Map<List<GoodsCategory>, List<GoodsCategoryVM>>(categorylist);
            categoryListVM.TotalCount = totalCount;

            categoryListVM.Categories = new StaticPagedList<GoodsCategoryVM>(categoryVMList, categoryListVM.PageIndex + 1, categoryListVM.PageSize, categoryListVM.TotalCount); ;

            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            return View(categoryListVM);

        }

        // GET: Admin/Pages/Details/5
        //public ActionResult Details(int? id)
        //{
        //    if (id == null)
        //    {
        //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        //    }

        //    Page page = _goodsCategoryService.GetById(id);
        //    if (page == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    return View(page);
        //}

        // GET: Admin/Pages/Create
        public ActionResult Create()
        {
            GoodsCategoryIM category = new GoodsCategoryIM
            {
                Active = true,
                Importance = 0
            };
            return View(category);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]      
        public JsonResult Create([Bind(Include = "Id,Title,Description,SeoName,Importance,Active,SEODescription,Keywords,Recommend,Thumbnail")] GoodsCategoryIM category)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {               
                var newCategory = _mapper.Map<GoodsCategoryIM, GoodsCategory>(category);
         
                _goodsCategoryService.Create(newCategory);

                if (!string.IsNullOrEmpty(category.Keywords) || !string.IsNullOrEmpty(category.SEODescription))
                {
                    var pageMeta = new PageMeta()
                    {
                        ObjectId = newCategory.Id.ToString(),
                        Keyword = category.Keywords.Replace('，', ','),
                        Description = category.SEODescription,
                        ModelType = ModelType.GOODSCATEGORY
                    };
                    _pageMetaService.Create(pageMeta);
                }

                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.GoodsCategory));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }

        public ActionResult Edit(int id)
        {         

            var category = _goodsCategoryService.GetById(id);
            if (category != null)
            {
                var editCategory = _mapper.Map<GoodsCategory, GoodsCategoryIM>(category);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.GOODSCATEGORY, editCategory.Id.ToString());
                if (pageMeta != null)
                {
                    editCategory.Keywords = pageMeta.Keyword;
                    editCategory.SEODescription = pageMeta.Description;
                }             
                return View(editCategory);
            }

            return new HttpStatusCodeResult(HttpStatusCode.NotFound);
        }



        [HttpPost]
        [ValidateAntiForgeryToken]

        public ActionResult Edit([Bind(Include = "Id,Title,Description,SeoName,Importance,Active,SEODescription,Keywords,Recommend,Thumbnail")] GoodsCategoryIM category)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);

            }

            try
            {
                var editCategory = _mapper.Map<GoodsCategoryIM, GoodsCategory>(category);

                _goodsCategoryService.Update(editCategory);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.GOODSCATEGORY, editCategory.Id.ToString());
                pageMeta = pageMeta ?? new PageMeta();


                if (!string.IsNullOrEmpty(category.Keywords) || !string.IsNullOrEmpty(category.SEODescription))
                {
                    pageMeta.ObjectId = category.Id.ToString();
                    pageMeta.Keyword = category.Keywords.Replace('，', ',');
                    pageMeta.Description = category.SEODescription;
                    pageMeta.ModelType = ModelType.GOODSCATEGORY;

                    if (pageMeta.Id > 0)
                    {
                        _pageMetaService.Update(pageMeta);
                    }
                    else
                    {
                        _pageMetaService.Create(pageMeta);
                    }
                }

                AR.SetSuccess(string.Format(Messages.AlertUpdateSuccess, EntityNames.GoodsCategory));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {
            var category = _goodsCategoryService.GetById(id);
            if (category != null)
            {
                category.Active = !category.Active;
                _goodsCategoryService.Update(category);

                AR.SetSuccess(String.Format(Messages.AlertActionSuccess, EntityNames.GoodsCategory));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            AR.Setfailure(String.Format(Messages.AlertActionFailure, EntityNames.GoodsCategory));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }



        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {
            var category = _goodsCategoryService.GetById(id);
            if (category != null)
            {
                _goodsCategoryService.Delete(category);

                AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.GoodsCategory));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            AR.Setfailure(String.Format(Messages.AlertDeleteFailure, EntityNames.GoodsCategory));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }
        [AllowAnonymous]
        public JsonResult IsSeoNameUnique(string seoName, int? Id)
        {
            return !IsExist(seoName, Id)
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous]
        public bool IsExist(string seoName, int? id)
        {
            var wType = _goodsCategoryService.GetAll().Where(w => w.SeoName == seoName);
            if (id > 0)
            {
                 wType = wType.Where(w=>w.Id != id);                       
            }
           
            if (wType.Count() > 0)
                return true;            
           
            return false;
        }
    }
}